import Axios from 'axios'
import store from "../store/index";
import { router } from '../router/index.js'
// import util from '../util/util'
import { Loading, Message, MessageBox } from "element-ui";

if (!store.state.token) {
  store.commit("token", sessionStorage.getItem("token"));
}

Axios.defaults.timeout = 60000;// 响应时间
Axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL;

Axios.interceptors.request.use((config) => {
  config.headers['Content-Type'] = 'application/json;charset=UTF-8';
  if (store.state.token && store.state.token != 'null') {
    config.headers['Authorization'] = "Bearer " + store.state.token;
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

Axios.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.reject(error);
});

/*
function toLogin () {
  let href = process.env.VUE_APP_UAT + encodeURIComponent(location.href) + '&response_type=code&state=123'
  location.href = href
}
*/
/**
 * 公共请求入口
 * @param param 'object'
 * @param url   'string'
 * @param type  'get || post'
 * @returns {Promise}
 */
export const commonPromise = ({ data, params, url, method = 'get' }) => {
  return new Promise((resolve, reject) => {
    Axios({ url, method, data, params }).then((res) => {
      if (res.status === 200) { // 成功
        if (res.data.code === 0 || res.data.code === 501 || res.data.code === 999 || res.data.code === 2001) {
          resolve(res.data)
        } else if (res.data.code === 103 || res.data.code === 104) {
          if (res.data && res.data.msg) {
            Message.error(res.data.msg)
          } else {
            // console.log(res.data.message)
            Message.error(res.data.message)
          }
          // console.log(res.data)
          resolve(res.data)
        } else if (res.data.code === 403 || res.data.code === 1004) {
          // util.clearStorage();
          res.data.msg && Message.error(res.data.msg);
          router.push('/login');
          // toLogin()
          reject(new Error('用户状态变更'));
        } else {
          Message.error(res.data)
          reject(res.data.msg)
        }
      } else if (res.status === 403) { // 用户状态变更
        // util.clearStorage();
        res.data.msg && Message.error(res.data.msg);
        // router.push('/login');
        // toLogin()
        reject(new Error('用户状态变更'));
      } else {
        res.data.msg && Message.error(res.data.msg);
        reject(new Error('系统出错'));
      }
    }).catch((err) => {
      Message.error('系统出错');
      reject(err);
    });
  })
}
